package cn.accjiyun.pki.controller.system;

import cn.accjiyun.pki.common.cache.EHCacheUtil;
import cn.accjiyun.pki.common.constants.CommonConstants;
import cn.accjiyun.pki.common.controller.BaseController;
import cn.accjiyun.pki.common.utils.CacheConstans;
import cn.accjiyun.pki.common.utils.MD5;
import cn.accjiyun.pki.common.utils.SingletonLoginUtils;
import cn.accjiyun.pki.common.utils.WebUtils;
import cn.accjiyun.pki.entity.SystemUser;
import cn.accjiyun.pki.service.SystemUserService;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by jiyun on 2017/5/1.
 */
@Controller
@RequestMapping("/admin")
public class LoginController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    private static String loginPage = getViewPath("/admin/main/login");//后台登录页面
    private static String registerPage = getViewPath("/admin/main/register"); //后台注册页面
    private static String loginSuccess = "redirect:/admin/main/main";//后台管理主界面

    @Autowired
    private SystemUserService systemUserService;

    @InitBinder({"systemUser"})
    public void initBinderSystemUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("systemUser.");
    }

    @RequestMapping
    public ModelAndView login(HttpServletRequest request) {
        SystemUser systemUser = SingletonLoginUtils.getLoginSystemUser(request);
        if (systemUser != null) return new ModelAndView(loginSuccess);
        return new ModelAndView(loginPage);
    }

    @RequestMapping("/main/register")
    public ModelAndView register() {
        return new ModelAndView(registerPage);
    }

    /**
     * 执行登录
     *
     * @param request
     * @return ModelAndView
     */
    @RequestMapping("/main/login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response,
                              @ModelAttribute("systemUser") SystemUser systemUser) {
        ModelAndView model = new ModelAndView();
        model.setViewName(loginPage);
        try {
            model.addObject("systemUser", systemUser);
            if (systemUser.getLoginName() == null || systemUser.getLoginName().trim().equals("")) {
                model.addObject("message", "请输入用户名!");
                return model;
            }
            if (systemUser.getPassword() == null || systemUser.getPassword().trim().equals("")) {
                model.addObject("message", "请输入密码!");
                return model;
            }

            //获取Session中验证码
            String randCode = (String) request.getSession().getAttribute(CommonConstants.RAND_CODE);
            //用户输入的验证码
            String randomCode = request.getParameter("randomCode");
            if (randomCode == null || !randomCode.equals(randCode)) {
                model.addObject("message", "验证码不正确！");
                return model;
            }
            request.getSession().removeAttribute(CommonConstants.RAND_CODE);
            systemUser.setPassword(MD5.getMD5(systemUser.getPassword()));
            SystemUser su = systemUserService.queryLoginUser(systemUser);
            if (su == null) {
                model.addObject("message", "用户名或密码错误！");
                return model;
            }
            if (su.getDisabled() == 1) {
                model.addObject("message", "该账号已被禁用！");
                return model;
            }
            //缓存用登录信息
            EHCacheUtil.set(CacheConstans.LOGIN_MEMCACHE_PREFIX + su.getId(), su);
            WebUtils.setCookie(response, CacheConstans.LOGIN_MEMCACHE_PREFIX,
                    CacheConstans.LOGIN_MEMCACHE_PREFIX + su.getId(), 1);
            model.setViewName(loginSuccess);
        } catch (Exception e) {
            model.addObject("message", "系统繁忙，请稍后再操作！");
            logger.error("LoginController.login()--error", e);
            model.setViewName(loginPage);
        }
        return model;
    }

    @RequestMapping("/main/addUser")
    public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response,
                                @ModelAttribute("systemUser") SystemUser systemUser) {
        ModelAndView model = new ModelAndView();
        model.setViewName(registerPage);
        try {
            if (!WebUtils.isValidateRealString(systemUser.getLoginName().trim())) {
                model.addObject("message", "请输入用户名!");
                return model;
            }
            if (!WebUtils.isValidateRealString(systemUser.getPassword().trim())) {
                model.addObject("message", "请输入密码!");
                return model;
            }

            //获取Session中验证码
            String randCode = (String) request.getSession().getAttribute(CommonConstants.RAND_CODE);
            //用户输入的验证码
            String randomCode = request.getParameter("randomCode");
            if (randomCode == null || !randomCode.equals(randCode)) {
                model.addObject("message", "验证码不正确！");
                return model;
            }
            boolean isValidate = systemUserService.validateLoginName(systemUser.getLoginName());
            if (!isValidate) {
                model.addObject("message", "用户名已存在！");
                return model;
            }
            systemUser.setPassword(MD5.getMD5(systemUser.getPassword()));
            systemUser.setUserRoleByRoleId(systemUserService.queryUserRoleById(0));
            systemUserService.createSystemUser(systemUser);
            model.addObject("message", "注册成功！");
        } catch (Exception e) {
            model.addObject("message", "系统繁忙，请稍后再操作！");
            logger.error("LoginController.addUser()--error", e);
            model.setViewName(registerPage);
        }
        model.setViewName(loginPage);
        return model;
    }

    /**
     * 后台用户退出登录
     *
     * @param request
     * @param response
     */
    @RequestMapping("/outLogin")
    public String outLogin(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.getSession().invalidate();
            int id = SingletonLoginUtils.getLoginSystemUserId(request);
            //删除所有的权限缓存
            EHCacheUtil.remove(CacheConstans.SYS_ALL_USER_FUNCTION_PREFIX + id);
            //删除登录用户的缓存信息
            EHCacheUtil.remove(CacheConstans.LOGIN_MEMCACHE_PREFIX + id);
            //删除登录用户权限缓存
            EHCacheUtil.remove(CacheConstans.USER_FUNCTION_PREFIX + id);
            //删除页面用户Cookie
            WebUtils.deleteCookie(request, response, CacheConstans.LOGIN_MEMCACHE_PREFIX);
            //清空所有的Session
            request.getSession().invalidate();
        } catch (Exception e) {
            logger.error("LoginController.outLogin()---error", e);
            return this.setExceptionRequest(request, e);
        }
        return "redirect:/admin/";
    }

    @RequestMapping("/getMenu.json")
    @ResponseBody
    public String getMenu(HttpServletRequest request) {
        try {
            SystemUser systemUser = SingletonLoginUtils.getLoginSystemUser(request);
            if (systemUser != null) {
                JsonParser jsonParser = new JsonParser();
                JsonObject menuJson = (JsonObject) jsonParser.parse(systemUser.getUserRoleByRoleId().getMenuJson());
                return gson.toJson(menuJson);
            }
        } catch (Exception e) {
            logger.error("LoginController.getMenu()--error", e);
        }
        return "{\"message\":\"你没有操作权限！\"}";
    }

}
